package cn.thoughtworks.school.programCenter.controllers;

import cn.thoughtworks.school.programCenter.annotations.Auth;
import cn.thoughtworks.school.programCenter.entities.ReviewQuiz;
import cn.thoughtworks.school.programCenter.entities.User;
import cn.thoughtworks.school.programCenter.exceptions.BusinessException;
import cn.thoughtworks.school.programCenter.repositories.ReviewQuizRepository;
import cn.thoughtworks.school.programCenter.services.QuizCenterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Date;
import java.util.Map;
import java.util.Objects;

@Controller
@RequestMapping(value = "/api")
public class HomeworkQuizController {

  @Autowired
  private ReviewQuizRepository reviewQuizRepository;
  @Autowired
  private QuizCenterService quizCenterService;

  @RequestMapping(value = "/v2/homeworkQuizzes/submission", method = RequestMethod.POST)
  public ResponseEntity submitHomeworkQuiz(@RequestBody Map map, @Auth User user) throws BusinessException {
    map.put("studentId", user.getId());

    return quizCenterService.submitHomeworkQuizAnswer(map);
  }

  @RequestMapping(value = "v2/homeworkQuizzes/submissions/{submissionId}/students/tasks/{taskId}/assignments/{assignmentId}/quizzes/{quizId}/runningLog", method = RequestMethod.GET)
  public ResponseEntity getHomeworkRunningLog(@PathVariable Long submissionId,
                                              @PathVariable Long assignmentId,
                                              @PathVariable Long taskId,
                                              @PathVariable Long quizId, @Auth User current) {
    Map result = quizCenterService.getHomeworkQuizzesLogs(submissionId, assignmentId, quizId, current.getId());
    if (Objects.isNull(result)) {
      return new ResponseEntity(HttpStatus.OK);
    }
    ReviewQuiz reviewQuiz = reviewQuizRepository.findByAssignmentIdAndQuizIdAndStudentId(assignmentId, quizId, current.getId());
    Object status = result.get("status");
    if (Objects.nonNull(status) && Objects.isNull(reviewQuiz)) {
        reviewQuiz = new ReviewQuiz(current.getId(), taskId, quizId, assignmentId, "已提交", new Date());
        reviewQuizRepository.save(reviewQuiz);
    }

    return new ResponseEntity<>(result, HttpStatus.OK);
  }

  @RequestMapping(value = "v2/homeworkQuizzes/{quizId}/answer", method = RequestMethod.GET)
  public ResponseEntity getHomeworkQuizzessAnswer(@PathVariable Long quizId) {
    Map quiz = quizCenterService.getHomeworkQuizById(quizId);
    return new ResponseEntity<>(quiz, HttpStatus.OK);
  }
}